package com.lancoo.cvas.config;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.lancoo.cvas.interceptor.ScheduleStatueInterceptor;
import com.lancoo.cvas.interceptor.SyncScheduleInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.lang.Nullable;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.config.annotation.*;

import javax.annotation.Resource;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author conor
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Resource
    private AuthenticationFilter authenticationFilter;
    @Bean
    public SyncScheduleInterceptor syncScheduleInterceptor(){
        return new SyncScheduleInterceptor();
    }

    @Bean
    public ScheduleStatueInterceptor scheduleStatueInterceptor(){
        return new ScheduleStatueInterceptor();
    }

    @Resource
    private LancooConfig lancooConfig;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/");
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedHeaders("*")
                .allowedMethods("*")
                .allowedOrigins("*")
                .allowCredentials(false);
    }

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }


    /**
     * 接口地址忽略大小写
     *
     * @param configurer
     */
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        AntPathMatcher matcher = new AntPathMatcher();
        matcher.setCaseSensitive(false);
        configurer.setPathMatcher(matcher);
        configurer.setUseTrailingSlashMatch(true);
    }


    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new Converter<String, Date>() {
            @Override
            public Date convert(@Nullable String source) {
                try {
                    if (StringUtils.isEmpty(source)) {
                        return null;
                    }
                    return new Date(Long.parseLong(source));
                } catch (Exception e) {
                    return null;
                }
            }
        });
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        //调用父类的配置
        WebMvcConfigurer.super.configureMessageConverters(converters);
        //创建FastJson的消息转换器
        FastJsonHttpMessageConverter convert = new FastJsonHttpMessageConverter();
        //创建FastJson的配置对象
        FastJsonConfig config = new FastJsonConfig();
        //对Json数据进行格式化
        config.setSerializerFeatures(SerializerFeature.PrettyFormat,
                SerializerFeature.WriteNullStringAsEmpty,
                SerializerFeature.WriteNullNumberAsZero,
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteNullBooleanAsFalse,
                SerializerFeature.WriteMapNullValue,
                //禁止循环引用
                SerializerFeature.DisableCircularReferenceDetect);
        config.setDateFormat("yyyy-MM-dd HH:mm:ss");
        config.setCharset(Charset.forName("UTF-8"));
        convert.setFastJsonConfig(config);
        convert.setSupportedMediaTypes(getSupportedMediaTypes());
        converters.add(convert);
    }

    public List<MediaType> getSupportedMediaTypes() {
        //创建fastJson消息转换器
        List<MediaType> supportedMediaTypes = new ArrayList<>();
        supportedMediaTypes.add(MediaType.APPLICATION_JSON);
        supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        supportedMediaTypes.add(MediaType.APPLICATION_ATOM_XML);
        supportedMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
        supportedMediaTypes.add(MediaType.APPLICATION_OCTET_STREAM);
        supportedMediaTypes.add(MediaType.APPLICATION_PDF);
        supportedMediaTypes.add(MediaType.APPLICATION_RSS_XML);
        supportedMediaTypes.add(MediaType.APPLICATION_XHTML_XML);
        supportedMediaTypes.add(MediaType.APPLICATION_XML);
        supportedMediaTypes.add(MediaType.IMAGE_GIF);
        supportedMediaTypes.add(MediaType.IMAGE_JPEG);
        supportedMediaTypes.add(MediaType.IMAGE_PNG);
        supportedMediaTypes.add(MediaType.TEXT_EVENT_STREAM);
        supportedMediaTypes.add(MediaType.TEXT_HTML);
        supportedMediaTypes.add(MediaType.TEXT_MARKDOWN);
        supportedMediaTypes.add(MediaType.TEXT_PLAIN);
        supportedMediaTypes.add(MediaType.TEXT_XML);
        supportedMediaTypes.add(MediaType.ALL);
        return supportedMediaTypes;
    }


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(authenticationFilter)
                .addPathPatterns("/**")
                .excludePathPatterns("/doc.html")
                .excludePathPatterns("/error")
                .excludePathPatterns("/swagger-resources/**")
                .excludePathPatterns("/webjars/**")
                .excludePathPatterns("/v2/**")
                .excludePathPatterns("/favicon.ico")
                .excludePathPatterns("/swagger-ui.html/**")
                .excludePathPatterns("/api/v5.0.1/web/yun/getUserInfo")
                .excludePathPatterns("/api/v5.0.1/web/yun/getUserInfoByToken")
                .excludePathPatterns("/api/v5.0.1/web/yun/getSystemUrl")
                .excludePathPatterns("/api/v5.0.1/web/yun/getTermInfo/**")
                .excludePathPatterns("/static/**")
                .excludePathPatterns("/api/v5.0.1/web/common/taskProgress/**")
                .excludePathPatterns("/api/v5.0.1/web/common/getSidebar")
                .excludePathPatterns("/api/v5.0.1/web/common/getDealTime")
                .excludePathPatterns("/api/v5.0.1/web/yun/getUserDetailInfoByToken")
                .excludePathPatterns("/api/v5.0.1/web/yun/getUserDetailInfoByToken")
                .excludePathPatterns("/api/v5.2.1/mobile/selectCourse/getUserDetailInfoByToken");

        registry.addInterceptor(syncScheduleInterceptor())
                .addPathPatterns("/api/v5.0.1/web/yun/syncScheduleToBasic")
                .addPathPatterns("/api/v5.0.1/web/yun/syncTeachingClassToBasic")
                .addPathPatterns("/api/v5.0.1/web/yun/syncOnlineScheduleToBasic");

        registry.addInterceptor(scheduleStatueInterceptor())
                .addPathPatterns("/api/v5.0.1/web/arrange/list/course")
                .addPathPatterns("/api/v5.0.1/web/arrange/arrangeStatistics");
    }


}
